package com.lwx.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(8090);
        while(true){
            final Socket socket = server.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                    final BufferedReader in = new BufferedReader(
                            new InputStreamReader(socket.getInputStream()));
                    final PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                    final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                       
                        //读
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                while(true){
                                    try {
                                        System.out.println("Client: " + in.readLine());
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }).start();
                        
                        //写
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                String request = "";
                                while(true){
                                    try {
                                        request = br.readLine();
                                        out.println(request);
                                    } catch (IOException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }).start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } 
                }
            }).start();
        }
    }
}
